<?php

namespace App\Admin\Controllers;

use App\Handlers\WithdrawalHandler;
use App\Models\UsersLeader;
use Dcat\Admin\Admin;
use Dcat\Admin\Auth\Permission;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\IFrameGrid;
use Dcat\Admin\Models\Administrator as AdministratorModel;
use Dcat\Admin\Models\Repositories\Administrator;
use Dcat\Admin\Show;
use Dcat\Admin\Support\Helper;
use App\Models\AdminUser;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Content;
use Config;
use App\Admin\Extensions\Tools\ReleasePost;
use Cache;


class MemberController extends BaseController
{

    public function title()
    {
        return trans('admin-user.labels.admin_user');
    }

    protected function grid()
    {
        return Grid::make(new AdminUser(), function (Grid $grid) {
            $grid->tableCollapse(false);
            $grid->responsive();
            $grid->setActionClass(Grid\Displayers\ContextMenuActions::class);
            $grid->model()->orderBy('id', 'desc');

            $grid->id('标识')->sortable();
            $grid->username(trans('admin-user.fields.username'));
            $grid->mt_login(trans('admin-user.fields.mt_login'));
            $grid->name(trans('admin-user.fields.name'));;
            $grid->en_name(trans('admin-user.fields.en_name'));
            $grid->tjr_id(trans('admin-user.fields.tjr_id'))->display(function ($v) {
                return AdminUser::where('id', $v)->first()->name ?? '公司帐户';
            })->label('success');

            $grid->model()->where(function ($query) {
                $query->whereHas('roles', function ($q) {
                    $q->where('id', 2);
                });
            });

            $grid->phone(trans('admin-user.fields.phone'));
            $grid->email;
            $grid->users_leader_id(trans('admin-user.fields.users_leader_id'))->display(function ($v) {
                $leader = UsersLeader::all()->pluck('leader', 'id')->toArray() + ['0' => '普通用户'];
                return $leader[$v];
            })->label('success');
            $grid->investment_amount(trans('admin-user.fields.investment_amount'));
            $grid->trade_balance(trans('admin-user.fields.trade_balance'));
            $grid->agent_balance(trans('admin-user.fields.agent_balance'));
            $grid->is_auth(trans('admin-user.fields.is_auth'))->using(['未认证', '已认证'])->label(['danger', 'success'], 3);
            $grid->is_lock(trans('admin-user.fields.is_lock'))->using([0 => '锁定', 1 => '正常'])->label([
                'danger', 'success'
            ], 3);
            $grid->created_at;

            // 按钮
            $grid->batchActions(function ($batch) {
                $batch->disableDelete();
            });


            $grid->quickSearch(['id', 'name', 'username']);
            $grid->showQuickEditButton();
            //$grid->disableCreateButton();


            $grid->actions(function ($actions) {
                $actions->disableEdit();
                if (Admin::user()->id != 1) {
                    $actions->disableDelete();
                }

                $token = md5(config('app.token').$this->id.config('app.token').date('YmdHi'));
                $url   = "/auth/hdlogin/$this->id/$token";

                // append一个操作
                $actions->append('<a href="'.$url.'" target="_blank" ><i class="fa fa-eye"></i> 登入</a>');

                // append一个操作
                Form::dialog('产品投入')
                    ->click('.create-form-'.$this->id) // 绑定点击按钮
                    ->url('member/'.$this->id.'/1') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
                    ->width('700px') // 指定弹窗宽度，可填写百分比，默认 720px
                    ->height('65%') // 指定弹窗高度，可填写百分比，默认 690px
                    ->success('Dcat.reload()'); // 新增成功后刷新页面
                // 当需要在同个“class”的按钮中绑定不同的链接时，把链接放到按钮的“data-url”属性中即可
                //$editPage = admin_base_path('admin_user/'.$id.'/edit');
                $actions->append("<div style='' ><span class='feather icon-log-in create-form-{$this->id}'> 投入 </span></div>"); // 新增成功后刷新页面

                Form::dialog('产品投出')
                    ->click('.out-form-'.$this->id) // 绑定点击按钮
                    ->url('member/'.$this->id.'/2') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
                    ->width('700px') // 指定弹窗宽度，可填写百分比，默认 720px
                    ->height('60%') // 指定弹窗高度，可填写百分比，默认 690px
                    ->success('Dcat.reload()'); // 新增成功后刷新页面
                // 当需要在同个“class”的按钮中绑定不同的链接时，把链接放到按钮的“data-url”属性中即可
                //$editPage = admin_base_path('admin_user/'.$id.'/edit');
                $actions->append("<div style='' ><span class='feather icon-log-out out-form-{$this->id}'> 投出 </span></div>"); // 新增成功后刷新页面

                if ($actions->getKey() == AdministratorModel::DEFAULT_ID) {
                    $actions->disableDelete();
                }
            });
        });
    }


    /**
     * 投入 页面
     *
     * @return Content
     */
    protected function editRujin($id, $type, Content $content)
    {
        return $content
            ->title($this->title())
            ->description('')
            ->body($this->rujin($type)->edit($id));
//            ->row(function (Row $row) use ($id) {
//                $row->column(12, function (Column $column) use ($id)  {
//                    $column->append($this->rujin()->edit($id));
//                });
//            });
    }

    /***
     * 实际修改投入
     * @param  AdminUser  $member
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function updateRujin(AdminUser $member)
    {
        return $this->rujin()->update($member->id);
    }

    /***
     * 投入 表单
     * @return Form
     */
    protected function rujin($amount_type = '')
    {
        return Form::make(new AdminUser(), function (Form $form) use ($amount_type) {
            $form->action(route('member.update-rujin', $form->getKey()));

            $form->text('name', trans('姓名'))->customFormat(function ($q) {
                return $q." ( $this->username )";
            })->disable();
            if ($amount_type == 1) {
                $form->text('amount', trans('admin.rjjer'))->required()->type('number');
                $form->radio('type', trans('投入类型'))->options(['1' => '正常投入', '2' => '赠送投入'])
                    ->rules('required')->customFormat(function ($value) {
                        return 1;
                    });
            } elseif ($amount_type == 2) {
                $form->text('amount', trans('投投出额'))->required()->type('number');
            }
            $form->date('created_at', trans('时间'))->customFormat(function () {
                return '';
            })->format('YYYY-MM-DD HH:mm:ss');

            $form->textarea('notes', trans('备注'))->required();
            $form->hidden('investment_amount', trans('admin.rjjer'));
            $form->hidden('id');
            $form->hidden('amount_type')->customFormat(function () use ($amount_type) {
                return $amount_type;// 判断投入还是投出 1投入2投出
            });
            $form->hidden('admin_id')->customFormat(function () {
                return Admin::user()->id;
            });


            $form->saving(function ($form) {
                if (!verifyWithdrawTime()) {
                    return $form->error('周五21点后 - 周六02点前系统结算中，不可出投入');
                }
            });

            $form->saving(function ($form) {
                $type = $form->type;
                if (empty($type) && $form->amount_type == 1) {
                    return $form->error('投入类型必选');
                }

                if (!$form->model()->is_auth && $form->amount_type == 2) {
                    return $form->error('客户资料未认证');
                }
                if ($form->amount_type == 1) { // 产品数量
                    $form->investment_amount += $form->amount;
                } else {
                    if ($form->amount_type == 2) { // 出投资金
                        if ($form->amount == 0 || $form->investment_amount < $form->amount) {
                            return $form->error('投入数量只有：'.$form->investment_amount);
                        }
                        $form->investment_amount -= $form->amount;
                    } else {
                        return $form->error('参数错误');
                    }
                }
                $form->deleteInput('amount');
                $form->deleteInput('notes');
                $form->deleteInput('type');
                $form->deleteInput('admin_id');
                $form->deleteInput('amount_type');
            });

            $form->saved(function ($form, $result) {
                $response = request()->all();
                if (!$result) {
                    recordUserLog('操作投入失败');
                    return $form->error('投入失败');
                }

                // 产品数量 大于等于3000 把等级改为DD
                $user = $form->repository()->eloquent();

                if ($response['amount_type'] == 1) { // 产品数量
                    if ($user->users_leader_id == 0 && $user->investment_amount >= 3000) {
                        $user->users_leader_id = 1;
                        $user->save();
                        recordUserLog('修改用户等级DD', json_encode($user, JSON_UNESCAPED_UNICODE));
                    }
                    if (WithdrawalHandler::inToOutLogMoney($response)) {
                        return WithdrawalHandler::inToOutDeposite($response);
                    }
                } else {
                    if ($response['amount_type'] == 2) {// 出投资金
                        if ($user->users_leader_id == 1 && $user->investment_amount < 3000) {
                            $user->users_leader_id = 0;
                            $user->save();
                            recordUserLog('修改用户等级普通用户', json_encode($user, JSON_UNESCAPED_UNICODE));
                        }
                        if (WithdrawalHandler::inToOutLogMoney($response, 2)) {
                            return WithdrawalHandler::inToOutDeposite($response);
                        }
                    }
                }
            });
        });
    }


    protected function iFrameGrid()
    {
        $grid = new IFrameGrid(new AdminUser());

        $grid->quickSearch(['id', 'name', 'username']);

        $grid->id->sortable();
        $grid->username;
        $grid->name;
        $grid->created_at;

        return $grid;
    }


    /***
     *  重构显示页面 用Tab 方式显示多页面
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('客户信息')
            // body 方法可以接受 Laravel 的视图作为参数
            ->row(function (Row $row) use ($id) {
                $row->column(6, function (Column $column) use ($id) {
                    $column->append($this->detail($id));
                });
            });
    }


    protected function detail($id)
    {
        // 验证是不是用户, 是往下
        verifyUserRole($id, true, '=');

        $admin_user = AdminUser::with('users_leader');
        return Show::make($id, $admin_user, function (Show $show) {
            $show->name(trans('admin-user.fields.name'));
            $show->en_name(trans('admin-user.fields.en_name'));
            $show->username(trans('admin-user.fields.username'))->label();
            $show->mt_login(trans('admin-user.fields.mt_login'));
            $show->tjr_id(trans('admin-user.fields.tjr_id'))->as(function ($q) {
                return AdminUser::where('id', $q)->first()->username ?? '顶级';
            })->label();
            $show->field('users_leader.leader', trans('等级'))->as(function ($q) {
                return $this->users_leader_id ? $this->users_leader['leader'] : '普通用户';
            });
            $show->phone(trans('admin-user.fields.phone'));
            $show->email(trans('admin-user.fields.email'))->prepend('mailto:');;
            $show->profit_rate(trans('admin-user.fields.profit_rate'));
            $show->sfz_id(trans('admin-user.fields.sfz_id'))->label();
            $show->sfz_zimg(trans('admin-user.fields.sfz_zimg'))->image('', '', 30);
            $show->sfz_fimg(trans('admin-user.fields.sfz_fimg'))->image('', '', 30);
            $show->bank_number(trans('admin-user.fields.bank_number'));
            $show->bank_type(trans('admin-user.fields.bank_type'));
            $show->bank_address(trans('admin-user.fields.bank_address'));
            $show->swift_code(trans('admin-user.fields.swift_code'));
            $show->is_lock(trans('admin-user.fields.is_lock'))->using([
                0 => trans('admin-user.fields.sd'), 1 => trans('admin-user.fields.zc')
            ])->dot([
                0 => 'danger',
                1 => 'success',
            ]);
            $show->is_auth(trans('admin-user.fields.is_auth'))->using([
                trans('admin-user.fields.yrz'), trans('admin-user.fields.wrz')
            ])->dot(['danger', 'success']);
            // 关闭编辑按钮
            $show->disableEditButton();
            // 关闭删除按钮
            $show->disableDeleteButton();
        });
    }


    /**
     * Create interface.
     *
     * @param  Content  $content
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description()['create'] ?? trans('admin.create'))
            ->row(function (Row $row) {
                $row->column(6, function (Column $column) {
                    $column->append($this->form());
                });
            });
    }


    public function form()
    {
        return Form::make(new AdminUser(['roles']), function (Form $form) {
            $userTable = config('admin.database.users_table');
            $connection = config('admin.database.connection');
            $id = $form->getKey();
            $form = $this->formButton($form);
            $form->disableDeleteButton();

            if (request()->path() != "hdcrm/member/create") {
                // 验证是不是管理员, 是往下
                verifyUserRole($id, true, '=');
            }

            if ($id) {
                $form->text('username', trans('admin.username'))
                    ->required()
                    ->creationRules(['required', "unique:{$connection}.{$userTable}"])
                    ->updateRules(['required', "unique:{$connection}.{$userTable},username,$id"]);
                $form->text('name', trans('admin.name'))->required();
                $form->password('password', trans('admin.password'))
                    ->minLength(5)
                    ->maxLength(20)
                    ->customFormat(function () {
                        return '';
                    });
                $form->password('pay_password', trans('admin.pay_password'))->customFormat(function () {
                    return '';
                });
            } else {
                $form->text('username', trans('admin.username'))
                    ->required()
                    ->creationRules(['required', "unique:{$connection}.{$userTable}"])
                    ->updateRules(['required', "unique:{$connection}.{$userTable},username,$id"]);
                $form->text('name', trans('admin.name'))->required();
                $form->password('password', trans('admin.password'))
                    ->required()
                    ->minLength(5)
                    ->maxLength(20);
                $form->password('pay_password', trans('admin.pay_password'))->required();
                $form->select('tjr_id', trans('users-leader.fields.tjr_id'))
                    ->options(function () {
                        return AdminUser::whereHas('roles', function ($q) {
                            $q->where('id', 2);
                        })->pluck('name', 'id')->toArray();
                    })->required();
            }
            //$form->ignore(['password_confirmation']);

            $form->select('users_leader_id', trans('users-leader.fields.leader'))
                ->options(function () {
                    return UsersLeader::all()->pluck('leader', 'id')->toArray() + ['0' => '普通用户'];
                });
            $form->radio('is_lock', trans('admin-user.fields.is_lock'))->options([
                '0' => '锁定', '1' => '正常'
            ])->default('1');
            $form->radio('is_withdrawal', trans('admin-user.fields.is_withdrawal'))->options([
                '0' => '否', '1' => '是'
            ])->default('1');
            $form->radio('is_mail', trans('admin-user.fields.is_mail'))->options([
                '0' => '否', '1' => '是'
            ])->default('1');
            $form->radio('is_auth', trans('admin-user.fields.is_auth'))->options([
                '0' => '未认证', '1' => '已认证'
            ])->default(0)->disable();
            $form->display('created_at', trans('admin.created_at'));
            $form->display('updated_at', trans('admin.updated_at'));
            $form->hidden('dry_password');
            $form->hidden('is_auth')->default(0);

            if ($id == AdministratorModel::DEFAULT_ID) {
                $form->disableDeleteButton();
            }

            $form->saving(function (Form $form) use ($id) {
                // 验证是不是用户, 是往下
                if (request()->path() != "hdcrm/member") {
                    if (!verifyUserRole($id, false, '=')) {
                        return $form->error('参数错误, 不可修改');
                    }
                }
                if (!$form->password) {
                    $form->deleteInput('password');
                } else {
                    $form->dry_passwork = encrypt(Config::get('app.dry_passwork').$form->password);
                    $form->password     = bcrypt($form->password);
                }
                if (!$form->pay_password) {
                    $form->deleteInput('pay_password');
                } else {
                    $form->pay_password = bcrypt($form->pay_password);
                }
            })->saved(function (Form $form) {
                $user = $form->repository()->eloquent();
                $user->roles()->sync([2], false);
            });
        });
    }

    public function destroy($id)
    {
        if (in_array(AdministratorModel::DEFAULT_ID, Helper::array($id))) {
            Permission::error();
        }

        // 验证是不是用户, 是往下
        if (!verifyUserRole($id, true, '=')) {
            return Admin::script(
                <<<JS
                Dcat.error('参数错误');
JS
            );
        }

        return parent::destroy($id);
    }
}
